var express = require('express');
var router = express.Router();
const db = require('../db/db');

router.post('/add', function (req, res, next) {
    // 获取当前用户学号
    let no = req.session.no
    // 获取pro_id
    let {id} = req.body;
    let sql = "insert into collection(no,item_id) values('" + no + "',(SELECT id as pro_id FROM projects WHERE id = '" + id + "'))"
    db(sql, function (err, result) {
        if (err) {
            res.send({flag: false, msg: "获取失败"});
            throw err;
        } else {
            res.json({flag: true, infoForm: result})
        }
    })
});

router.post('/del', function (req, res, next) {
    let {id} = req.body;
    console.log(id)
    let sql = `delete
               from collection
               where id = ${id}`;
    db(sql, function (err, result) {
        if (err) {
            res.send({flag: false, msg: "获取失败"});
            throw err;
        } else {
            res.json({flag: true, infoForm: result})
        }
    })
});

router.post('/', function (req, res, next) {
    let {page, pageSize} = req.body;
    let no = req.session.no
    let start = (page - 1) * pageSize;
    let sql = `select i.id as id,i.name as name,type,detail,\`condition\`,path,starttime,endtime,\`require\`,c.Id as cid,
       (select count(*) from \`collection\` where collection.no = ${no}) as total
        from item i,\`collection\` c
        WHERE i.id = c.item_id and c.no = ${no}
        ORDER BY c.id limit ${start},${pageSize}`
    db(sql, function (err, rows) {
        if (err) {
            res.render('error.html', {title: 'Express', datas: []});
        } else {
            res.json({datas: rows, total: rows[0]['total']});
        }
    })
});

module.exports = router;
  